//
//  DashboardViewController.swift
//  CheckmeRing
//
//  Created by 董鹏 on 2022/2/27.
//

import UIKit

class DashboardUploadViewController: RViewController {

    @IBOutlet weak var apiUrl: UITextField!
    @IBOutlet weak var userId: UITextField!
    @IBOutlet weak var password: UITextField!
    /// 自动同步
    @IBOutlet weak var syncroSwitch: UISwitch!
    /// 时间间隔
    @IBOutlet weak var timeInterval: UITextField!
    /// 前缀
    @IBOutlet weak var prefix: UITextField!
    /// 后缀
    @IBOutlet weak var suffix: UITextField!
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.isUserInteractionEnabled = true
        self.view.addGestureRecognizer(UITapGestureRecognizer.init(target: self, action: #selector(viewEndEditing)))
        
        if CacheManager.manager.containsObject(forKey: OnlineUploadConfig), let config = CacheManager.manager.getValueForKey(OnlineUploadConfig) as? UploadConfig {
            
            self.apiUrl.text = config.apiUrl
            self.password.text = config.password
            self.userId.text = config.userId
            self.syncroSwitch.isOn = config.auto
            
            self.timeInterval.text = config.interval
            self.suffix.text = config.suffix
            self.prefix.text = config.prefix
            
        }
        
    }
    
    /// 回收键盘
    @objc func viewEndEditing() {
        self.view.endEditing(true)
    }
    
    @IBAction func saveBtnDidClicked(_ sender: Any) {
        
        self.viewEndEditing()
        if self.apiUrl.text?.count == 0 || self.userId.text?.count == 0 || self.password.text?.count == 0 {
            self.view.showYCToast(message: "すべての項目に入力してください。 API URL/ユーザーID/パスワード")
        }
        
        let service = FBYHomeService.init()
        service.searchMessage("post", andWithDic: ["userid": self.userId.text!, "password": self.password.text!], andUrl: self.apiUrl.text!) { result in
            
            // 成功
            if result == "received spot check datafile processed" {
                self.view.showYCToast(message: "アップロード可能です。")
                
                let uploadConfig = UploadConfig.init(fromDictionary: [
                    "apiUrl": self.apiUrl.text!,
                    "userId": self.userId.text!,
                    "password": self.password.text!,
                    "interval": self.timeInterval.text ?? 3,
                    "prefix": self.prefix.text ?? "",
                    "suffix": self.suffix.text ?? "",
                    "auto": self.syncroSwitch.isOn
                ])
                CacheManager.manager.setValueForKey(OnlineUploadConfig, uploadConfig as NSCoding)
                
            }else if result == "received realtime data processed" {
                self.view.showYCToast(message: "HistoryクラウドアップロードのAPI URLが入力されています。DashboardクラウドアップロードのAPI URLを入力してください。")
            }else {
                self.view.showYCToast(message: "API URLに誤りがあるか、エラーが発生しています。200")
            }
            
        } andFailure: { error in
            self.view.showYCToast(message: "ユーザーIDまたはパスワードに誤りがあります。")
        }
        
    }
    
    override func popToBeforeViewController() {
        if self.apiUrl.text?.count == 0 || self.userId.text?.count == 0 || self.password.text?.count == 0 {
            self.view.makeToast("すべての項目に入力してください。 API URL/ユーザーID/パスワード")
        }else {
            self.navigationController?.popViewController(animated: true)
        }
    }
    
    
    @IBAction func scanBtnDidClicked(_ sender: UIButton) {
        
        let vc = ScanViewController.init()
        vc.backData = { result in
            self.apiUrl.text = result.apiurl ?? ""
            self.userId.text = result.userid ?? ""
            self.password.text = result.password ?? ""
        }
        self.navigationController?.pushViewController(vc, animated: false)
    }
    
}
